<?php
namespace adminmatrix\server\app\middleware;
use adminmatrix\server\app\lists\BaseListsData;
use think\Model;
use think\model\Collection;
use think\Response;
use think\facade\Db;
class ReturnMiddleware
{

   public function handle($request , \Closure $next){
        // 执行下一个中间件或控制器
        $response = $next($request);
        // 获取响应数据

        $result = false;
        $data = [
            'code'      =>  $response->getCode(),
            'message'   =>  $response,
        ];
        if ($response->getData() instanceof  Model){

        } else if($this->isModel($response->getData())){

        } else if($response->getData() instanceof  Collection)
        {
            $result = true;
            $data['data']   =  $model =  $response->getData();
            $data['test']   =   $model->fetchSql(true);
        }
        $parentClass = @class_parents($response->getData());

        // 判断是否是 BaseListsData 类的实例
        if (isset($parentClass[BaseListsData::class]))
        {
            $parentClass = @class_parents($response->getData()->lists());
            if (isset($parentClass['adminmatrix\server\app\model\BaseModel']))
            {
                $result = true;
                $data['data']   =  [
                    'lists'     =>  $response->getData()->lists()->select(),
                    'total'     =>  $response->getData()->count(),
                    'page'      =>  $request->get('page' , '1'),
                    'pageSize' =>  $request->get('pageSize', '10'),
                ];

                if (env('app_debug'))
                {
                    $data['sql'] =  Db::getLastSql();
                }
            }

        }
        if ($result)
        {
            return Response::create([...$data,
                'response_time' =>  time()
            ] , 'json');
        }

        return $response;

   }

   protected function isModel($object)
   {
       return $object instanceof  Model;
   }
}